<?php require 'pis.php'; ?>
<?php

class MyInstaller extends PIS {
	
  function page_welcome(){		

    $this->message('Welcome to MGBlog installer. ');

    $this->message('The next couple of pages will guide you '.
      'through the installation process.');

  }

  function page_license(){
     $this->input('agreement','agreement',array('required'=>true,'file'=>'license.txt'));
  }

  function page_test(){
    
  	$mysql = false;
  	
  	if (extension_loaded('mysql') || extension_loaded('mysqli')) 
  	{
    	$mysql = true;
    }
    
    $php = false;
    
    if(substr(PHP_VERSION,0,1) === "5")
    {
    	$php = true;	
    }
    
    $this->title("Requirements Check");
	
    if ( $this->test($mysql,'PHP has no support for mysql or MySQL extension not loaded!'))
    {
        $this->message('Mysql extension loaded!','passed');
    }
	
    if ( $this->test($php,'PHP Version is 5!') )
    {
        $this->message('PHP Version >= 5!','passed');
    }
	
    if($mysql && $php)
    {
    	$this->message('Your system meets MGBlog\'s requirements!');
    	$this->message('You can now continue with installation.');
    }
    else
    {
    	$this->message('Your system does NOT meet MGBlog\'s requirements!');
    	$this->message('Please, change your system settings and then restart this installer.');
    }
  
  }

  function page_config(){
    
    $this->title("Configuration Options");

    $this->input('text','DB_DOMAIN',array(
	   'required' => true,
	   'label' => 'Database Host',
       'size' => 25,
	   'help' => 'Commonly localhost. You can test the test() function by putting something other than localhost.',
	   ));

    $this->input('text','DB_USER',array(
	   'required' => true,
	   'label' => 'Database Username',
       'size' => 25,
	   'help' => 'Your username password.'
	   ));

    $this->input('text','DB_PASS',array(
	   'required' => true,
	   'label' => 'Database Password',
       'size' => 25,
	   'help' => 'Your database password.'
	   ));

    $this->input('text','DB_NAME',array(
	   'required' => true,
	   'label' => 'Database Name',
       'size' => 25,
	   'help' => 'Database name to created tables in.'
	   ));

	$this->input('text','SERVER',array(
	   'required' => true,
	   'label' => 'Server name',
	   'value' => $_SERVER['SERVER_NAME'],
       'size' => 25,
	   'help' => 'Server name - without http:// and TLD'
	   ));
	   
	$this->input('text','USER',array(
	   'required' => true,
	   'label' => 'Blog admin username',
       'size' => 25,
	   'help' => 'Admin username.'
	   ));
	   
	$this->input('text','PASS',array(
	   'required' => true,
	   'label' => 'Blog admin password',
       'size' => 25,
	   'help' => 'Admin password.'
	   ));
  }

  function page_installation()
  {  
  	ini_set("display_errors", "Off");
    
    if ( $this->test(($this->get('DB_DOMAIN') == 'localhost'),'Database host must be localhost') )
    {
    	//set some config settings
    	
    	//NEED MORE TESTING!
    	
    	//root blog folder
    	$rootBlog = substr($_SERVER['SCRIPT_FILENAME'],0,strripos($_SERVER['SCRIPT_FILENAME'],'/')+1);
    	$this->set("ROOT",$rootBlog); 
    	
    	//gallery upload dir
    	$this->set("UPLOAD_DIR",$rootBlog.'gallery/');
    	
    	//website root URL address
    	//use PHP_SELF?
    	$root = substr($_SERVER['SCRIPT_NAME'],0,strripos($_SERVER['SCRIPT_NAME'],'/')+1);
    	$website = "http://".$this->get('SERVER')."$root";
    	$this->set("WEBSITE_URL",$website);
    	
    	//generate random salt
    	$salt = sha1(uniqid(rand(), true));
       	
    	//set salt to be written to config file
    	$this->set("SALT",$salt);
    	
    	//calculate password
    	$encsalt = sha1($salt);
    	$pwd = sha1(sha1($encsalt.$this->get("PASS").$encsalt));
       	
		$exceptions = array();
		
		$exceptions[] = "USER";
    	$exceptions[] = "PASS";
    	$exceptions[] = "SERVER";

    	if($this->test($this->makeConfig("define('{\$name}',{\$value});\n",'',"config.php",$exceptions),"Writing config file failed. Make sure, directory permission is properly set."))
    	{
    		$this->message("Config file written succesfully!");
    	}

    	$connection = mysql_connect($this->get("DB_DOMAIN"),$this->get("DB_USER"),$this->get("DB_PASS"));
    	mysqli_multi_query();
    	if($this->test($connection,"Cannot connect to database! Please, return to previous page and check database host, username and password."))
    	{
    		$this->message("Connection to database successfull!");
    	}

    	if($this->test(mysql_query("CREATE DATABASE IF NOT EXISTS ".$this->get("DB_NAME"),$connection),"Cannot create database or database already exists!"))
    	{
    		$this->message("Database ".$this->get("DB_NAME") ." created succesfully!");
    	}

    	if($this->test(mysql_select_db($this->get("DB_NAME"),$connection),"Couldn't select database. Please, check database configuration."))
    	{
    		$this->createDatabase($pwd,$connection);
    	}

    	mysql_close($connection);
    }

  }

  function page_complete() 
  {
  	 	$this->title('Installation Complete');
  	 	$this->message('Congratulations!');
  	 	$this->message('You have succesfully installed MGBlog!');
        $this->message('For security reasons, please remove the installation files ( <strong>install.php</strong>, <strong>pis.php</strong>,  and <strong>license.txt</strong>) from the root directory.');
        $this->message('Happy blogging!');
  }
  
  //since importSQL is not working, ugly hack is needed
  function createDatabase($pwd,$connection) 
  {
  		mysql_query("CREATE TABLE IF NOT EXISTS `albums` (
			  `id` tinyint(11) unsigned NOT NULL auto_increment,
			  `title` text NOT NULL,
			  `description` longtext NOT NULL,
			  `thumb` text NOT NULL,
			  `date` datetime NOT NULL,
			  PRIMARY KEY  (`id`)
			) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=10 ;
    	",$connection);
    	
    	mysql_query("CREATE TABLE IF NOT EXISTS `category` (
		  `id` int(11) unsigned NOT NULL auto_increment,
		  `name` varchar(55) NOT NULL,
		  PRIMARY KEY  (`id`)
		) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
    	",$connection);
    	
    	mysql_query("CREATE TABLE IF NOT EXISTS `comments` (
		  `id` int(10) unsigned NOT NULL auto_increment,
		  `parentid` int(10) unsigned default NULL,
		  `body` text,
		  `author` varchar(50) default NULL,
		  `email` varchar(50) NOT NULL,
		  `link` text NOT NULL,
		  `date` datetime default NULL,
		  `flag` tinyint(11) unsigned NOT NULL,
		  PRIMARY KEY  (`id`)
		) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=16 ;
    	",$connection);
    	
    	mysql_query("CREATE TABLE IF NOT EXISTS `links` (
		  `id` tinyint(11) unsigned NOT NULL auto_increment,
		  `name` varchar(55) NOT NULL,
		  `link` longtext NOT NULL,
		  PRIMARY KEY  (`id`)
		) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
    	",$connection);
    	
    	mysql_query("CREATE TABLE IF NOT EXISTS `members` (
		  `id` int(4) NOT NULL auto_increment,
		  `username` varchar(65) NOT NULL default '',
		  `password` varchar(65) NOT NULL default '',
		  PRIMARY KEY  (`id`)
		) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
    	",$connection);
    	
    	mysql_query("CREATE TABLE IF NOT EXISTS `pictures` (
			  `id` int(10) unsigned NOT NULL auto_increment,
			  `description` longtext NOT NULL,
			  `thumb` text NOT NULL,
			  `date` datetime NOT NULL,
			  `parentid` int(11) NOT NULL,
			  `image` text NOT NULL,
			  PRIMARY KEY  (`id`)
			) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=142 ;
    	",$connection);
    	
    	mysql_query("
			CREATE TABLE IF NOT EXISTS `posts` (
			  `id` int(10) unsigned NOT NULL auto_increment,
			  `title` varchar(50) default NULL,
			  `body` text,
			  `date` datetime default NULL,
			  `catid` int(11) unsigned NOT NULL,
			  PRIMARY KEY  (`id`)
			) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=48 ;
    	",$connection);
    	
    	mysql_query("CREATE TABLE IF NOT EXISTS `pref` (
			  `title` varchar(65) NOT NULL,
			  `description` varchar(65) NOT NULL,
			  `theme` varchar(55) NOT NULL,
			  `use_akismet` tinyint(1) NOT NULL,
			  `akismet_key` varchar(55) NOT NULL,
			  `use_captcha` tinyint(1) NOT NULL,
			  `posts_per_page` varchar(55) NOT NULL,
			  `albums_per_page` varchar(55) NOT NULL,
			  `pictures_per_page` varchar(55) NOT NULL
			) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
    	",$connection);
    	
    	mysql_query("CREATE TABLE IF NOT EXISTS `spage` (
			  `id` int(11) unsigned NOT NULL auto_increment,
			  `name` varchar(55) NOT NULL,
			  `body` longtext NOT NULL,
			  PRIMARY KEY  (`id`)
			) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
    	",$connection);
    	
    	mysql_query("INSERT INTO `albums` VALUES (7, 'Test album1', '<p>Test album with some pictures.</p>', 'thumb_winona-ryder-1920x1200-31038.jpg', '2008-07-16 21:24:21');",$connection);
		mysql_query("INSERT INTO `albums` VALUES (6, 'Test album 2', '<p>Another test album with some more pictures.</p>', 'thumb_jessica-biel-1920x1200-21336.jpg', '2008-07-16 21:24:27');",$connection);
		mysql_query("INSERT INTO `albums` VALUES (9, 'Test album', '<p>Empty test album.</p>', '', '2008-09-10 14:58:57');",$connection);
    	
    	mysql_query("INSERT INTO `pref` VALUES ('Hua!', 'kukulelegofelj', 'helloblogger', 0, '', 1, '11', '11', '3');
    	",$connection);
    	
    	mysql_query("INSERT INTO `category` VALUES (7, 'Test category');
    	",$connection);
    	
    	mysql_query("INSERT INTO `links` VALUES (3, 'Test link', 'http://www.google.com');
    	",$connection);
    	
    	mysql_query("INSERT INTO `spage` VALUES (4, 'Test page', '<p><em>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</em></p>');
    	",$connection);
    	
    	mysql_query("INSERT INTO `posts` VALUES (47, 'Test post', '<p><em>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</em></p>', '2008-09-10 00:00:00', 7);
    	",$connection);
    		
    	mysql_query("INSERT INTO `pictures` VALUES (112, '', 'thumb_grace-park-1920x1200-22893.jpg', '2008-07-16 21:26:50', 6, 'grace-park-1920x1200-22893.jpg');",$connection);
		mysql_query("INSERT INTO `pictures` VALUES (113, '', 'thumb_holly-valance-1600x1200-1822.jpg', '2008-07-16 21:26:52', 6, 'holly-valance-1600x1200-1822.jpg');",$connection);
		mysql_query("INSERT INTO `pictures` VALUES (114, '', 'thumb_holly-valance-1600x1200-5726.jpg', '2008-07-16 21:32:03', 6, 'holly-valance-1600x1200-5726.jpg');",$connection);
		mysql_query("INSERT INTO `pictures` VALUES (115, '', 'thumb_holly-valance-1920x1200-21645.jpg', '2008-07-16 21:32:05', 6, 'holly-valance-1920x1200-21645.jpg');",$connection);
		mysql_query("INSERT INTO `pictures` VALUES (116, '', 'thumb_holly-valance-1920x1200-23917.jpg', '2008-07-16 21:32:06', 6, 'holly-valance-1920x1200-23917.jpg');",$connection);
		mysql_query("INSERT INTO `pictures` VALUES (117, '', 'thumb_holly-valance-1600x1200-16031.jpg', '2008-07-16 21:32:08', 6, 'holly-valance-1600x1200-16031.jpg');",$connection);
		mysql_query("INSERT INTO `pictures` VALUES (118, '', 'thumb_jessica-alba-1920x1200-21462.jpg', '2008-07-16 21:33:43', 6, 'jessica-alba-1920x1200-21462.jpg');",$connection);
		mysql_query("INSERT INTO `pictures` VALUES (120, '', 'thumb_jessica-alba-1920x1200-23309.jpg', '2008-07-16 21:33:46', 6, 'jessica-alba-1920x1200-23309.jpg');",$connection);
		mysql_query("INSERT INTO `pictures` VALUES (121, '', 'thumb_jessica-biel-1920x1200-21337.jpg', '2008-07-16 21:36:18', 6, 'jessica-biel-1920x1200-21337.jpg');",$connection);
		mysql_query("INSERT INTO `pictures` VALUES (141, '', 'thumb_winona-ryder-1920x1200-31038.jpg', '2008-08-15 14:33:40', 7, 'winona-ryder-1920x1200-31038.jpg');",$connection);
    	
    		
    	$usr = $this->get('USER');
    	//username & password!
    	mysql_query("INSERT INTO `members` VALUES (1, '$usr', '$pwd');
    	",$connection);
  }
  
}

$installer = new MyInstaller('MGBlog installer');

?><?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title><?php echo $installer->title; ?></title>
<style type="text/css">
/* default style */
body {font-family: tahoma, arial; font-size: 0.9em}

label {width: 150px; float: left; text-align: right; margin-right: 5px; font-family: verdana; }
label.required {font-weight: bold; font-style: italic;}

h1 {width: 600px; text-align: left; font-family:verdana; font-size: 1.6em; margin: 10% 0px 0px 0px; background-color: #303030; padding: 3px; color: #f0f0f0;}
h2 {border-bottom: 1px solid black; margin: 0px 10px 0px 10px; }

input, textarea, select { border: 1px solid black; float: left; }

hr {border:1px solid black;}

.message { margin-bottom: 10px;}

#page {background-color: #CDBAEC; width: 600px; text-align:left; padding: 3px; padding-top: 10px; }
#main {padding: 10px; }

#navigation {border-top: 1px solid black; margin: 5px 10px 0px 10px; padding: 5px;}
#navigation input {float: right; margin-left: 10px;}

#footer {padding: 3px; width: 600px; background-color: #f0f0f0; text-align: left; font-size: 0.7em; color: #AAAAAA;}

.error,
.field .error { color: red; font-weight: bold; font-size: 0.8em; }
.field .error { display: inline; margin-left: 10px; }

.field { margin-top: 10px;}
.help {padding:2px; float: left; font-weight: bold; margin-left: 10px; }


</style>
</head>
<body>
<div align="center">

<?php  $installer->run(); ?>

</div>
</body>
</html>